package projectwork.shchuangge.cn.com.newproject.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Response;
import projectwork.shchuangge.cn.com.newproject.R;
import projectwork.shchuangge.cn.com.newproject.been.UpDataInfoBeen;
import projectwork.shchuangge.cn.com.newproject.content.URIpsot;
import projectwork.shchuangge.cn.com.newproject.ui.fragment.BagFragment;
import projectwork.shchuangge.cn.com.newproject.ui.fragment.HomeFragment;
import projectwork.shchuangge.cn.com.newproject.ui.fragment.MeFragment;
import projectwork.shchuangge.cn.com.newproject.ui.fragment.ShoppingFragment;
import projectwork.shchuangge.cn.com.newproject.uitls.FragementFactory;
import projectwork.shchuangge.cn.com.newproject.uitls.GsonUtil;
import projectwork.shchuangge.cn.com.newproject.uitls.HttpUtil;
import projectwork.shchuangge.cn.com.newproject.uitls.PackageUtil;
import projectwork.shchuangge.cn.com.newproject.uitls.ToastMake;

public class MainActivity extends AppCompatActivity implements View.OnClickListener ,
        ActivityCompat.OnRequestPermissionsResultCallback {
    //这是安装界面的请求码
    private static final int    REQUEST_INSTALL = 100;
    private static final String TAG             = "MainActivity";

    //记录两次回退键直接退出
    private long tempTime = 0;
    private UpDataInfoBeen mInfoBeen;
    private boolean        mEquals;
    private InputStream      mInputStream  = null;
    private FileOutputStream mOutputStream = null;
    private ProgressDialog mProgressDialog;
    private long           greelong;
    private File           mAPKfile;

    private FragmentTransaction mFragmentTransaction;
    private ImageView           firstHomeImage;
    private TextView            firstHomeText;
    private LinearLayout        firstHomeHome;
    private ImageView           secondShoppingImage;
    private TextView            secondShoppingText;
    private LinearLayout        secondShoppingShopping;
    private ImageView           tiredBagImage;
    private TextView            tiredBagText;
    private LinearLayout        tiredBagBag;
    private ImageView           fourMeImage;
    private TextView            fourMeText;
    private LinearLayout        fourMeMe;
    private HomeFragment        mFragment;
    private ShoppingFragment    shoppingFragment;
    private BagFragment         bagFragment;
    private MeFragment          meFragment;
    private BagFragment         mBagFragment;
    private HomeFragment        mHomeFragemt;
    private MeFragment          mMeFragment;
    private ShoppingFragment    mShoppingFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //6.0新特性，动态获取权限
        getUserPermission();

        //进行版本更新
        initData();
        //对控件进行操作
        initView();
        //初始化默认所有的按钮背景都是灰色的
        noPressed();

        //默认首页先被选中
        mFragmentTransaction = getSupportFragmentManager().beginTransaction();
        mFragment = FragementFactory.getHomeFragemt();
        if (mFragment.isAdded()) {
            mFragmentTransaction.remove(mFragment);
        }
        mFragmentTransaction.add(R.id.mian_mian_mian, mFragment, "one").commit();
        //按钮背景也要改变
        firstHomeText.setTextColor(Color.parseColor("#a154bc"));
        firstHomeImage.setImageResource(R.mipmap.home_on);

    }

    /**
     * 将所有的字体颜色设置为未选中
     */
    private void noPressed() {
        firstHomeText.setTextColor(Color.parseColor("#333333"));
        secondShoppingText.setTextColor(Color.parseColor("#333333"));
        tiredBagText.setTextColor(Color.parseColor("#333333"));
        fourMeText.setTextColor(Color.parseColor("#333333"));

        firstHomeImage.setImageResource(R.mipmap.home_off);
        secondShoppingImage.setImageResource(R.mipmap.shopping_off);
        tiredBagImage.setImageResource(R.mipmap.shopping_bag_off);
        fourMeImage.setImageResource(R.mipmap.mine_off);
    }

    private void initView() {
        firstHomeImage = (ImageView) findViewById(R.id.first_home_image);
        firstHomeText = (TextView) findViewById(R.id.first_home_text);
        firstHomeHome = (LinearLayout) findViewById(R.id.first_home_home);
        firstHomeHome.setOnClickListener(MainActivity.this);

        secondShoppingImage = (ImageView) findViewById(R.id.second_shopping_image);
        secondShoppingText = (TextView) findViewById(R.id.second_shopping_text);
        secondShoppingShopping = (LinearLayout) findViewById(R.id.second_shopping_shopping);
        secondShoppingShopping.setOnClickListener(MainActivity.this);

        tiredBagImage = (ImageView) findViewById(R.id.tired_bag_image);
        tiredBagText = (TextView) findViewById(R.id.tired_bag_text);
        tiredBagBag = (LinearLayout) findViewById(R.id.tired_bag_bag);
        tiredBagBag.setOnClickListener(MainActivity.this);

        fourMeImage = (ImageView) findViewById(R.id.four_me_image);
        fourMeText = (TextView) findViewById(R.id.four_me_text);
        fourMeMe = (LinearLayout) findViewById(R.id.four_me_me);
        fourMeMe.setOnClickListener(MainActivity.this);

    }

    @Override
    public void onClick(View view) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        mBagFragment = FragementFactory.getBagFragment();
        mHomeFragemt = FragementFactory.getHomeFragemt();
        mMeFragment = FragementFactory.getMeFragment();
        mShoppingFragment = FragementFactory.getShoppingFragment();
        transaction.hide(mBagFragment);
        transaction.hide(mHomeFragemt);
        transaction.hide(mMeFragment);
        transaction.hide(mShoppingFragment);


        //在点击的时候，先设置权不足为无按压状态
        noPressed();
        switch (view.getId()) {
            case R.id.first_home_home:

                if (!mFragment.isAdded()) {
                    transaction.add(R.id.mian_mian_mian, mFragment, "one");
                }
                transaction.show(mHomeFragemt);
                firstHomeText.setTextColor(Color.parseColor("#a154bc"));
                firstHomeImage.setImageResource(R.mipmap.home_on);
                break;
            case R.id.second_shopping_shopping:

                if (!mShoppingFragment.isAdded()) {
                    transaction.add(R.id.mian_mian_mian, mShoppingFragment, "one");
                }
                transaction.show(mShoppingFragment);
                secondShoppingText.setTextColor(Color.parseColor("#a154bc"));
                secondShoppingImage.setImageResource(R.mipmap.shopping_on);
                break;
            case R.id.tired_bag_bag:
                if (!mBagFragment.isAdded()) {
                    transaction.add(R.id.mian_mian_mian, mBagFragment, "one");
                }
                transaction.show(mBagFragment);
                tiredBagText.setTextColor(Color.parseColor("#a154bc"));
                tiredBagImage.setImageResource(R.mipmap.shopping_bag_on);
                break;
            case R.id.four_me_me:

                if (!mMeFragment.isAdded()) {
                    transaction.add(R.id.mian_mian_mian, mMeFragment, "one");
                }
                transaction.show(mMeFragment);
                fourMeText.setTextColor(Color.parseColor("#a154bc"));
                fourMeImage.setImageResource(R.mipmap.mine_on);

                break;

        }
        transaction.commit();

    }

    //判断按下的是否为返回键，并且是否按下

    /**
     * 这是退出工具
     *
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
                        this.finish();
                        return true;}
        if ((keyCode == KeyEvent.KEYCODE_BACK) &&
                (event.getAction() == KeyEvent.ACTION_DOWN)) {
            //如果两次按返回键时间间隔大于2000毫秒就吐司提示，否则finish（）当前Activity

            if ((System.currentTimeMillis() - tempTime) > 2000) {
                tempTime = System.currentTimeMillis();
                ToastMake.showToast("再按下就会退出.....");
            } else {
                finish();
                System.exit(0);//0表示正常退出，非0表示不正常
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取本地版本号，并进行更新
     */
    private void initData() {

        //不能再主线程中进行操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //1.进行网络请求获取json数据
                    Response response = HttpUtil.httpGet(URIpsot.apkDown);

                    String json = response.body().string();

                    //json解析
                    mInfoBeen = GsonUtil.parseJsonToBean(json, UpDataInfoBeen.class);
                    String version = mInfoBeen.getRemoteVersion();
                    int anInt = Integer.parseInt(version);

                    //2.进行版本号比对
                    int code = PackageUtil.getVersionCode(MainActivity.this, getPackageName());
                    if (anInt > code) {
                        //                    3.切换到主线程弹出提示框进行提示

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                //展示对话框
                                dailogShow();
                            }
                        });

                    } else {
                        //TODO:进入主界面

                    }

                } catch (Exception e) {
                    //TODO：返回到主界面
                    e.printStackTrace();

                }
            }
        }).start();
    }

    //                    4.是否进行升级
    private void dailogShow() {

        AlertDialog.Builder builder = new AlertDialog.Builder(
                MainActivity.this);
        builder.setTitle("版本更新提示");
        builder.setMessage(mInfoBeen.getDesc());
        // 4.是否升级
        builder.setPositiveButton("立刻升级", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //开始更新
            dialog.dismiss();
            //  5.下载apk
            //弄个进度框，显示下载速度
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.show();
            //先判断sd卡是否存在
            mEquals = Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    downLadeApk();
                }
            }).start();

            }
        });
        builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //                        //取消更新
                //                        //TODO:进入主界面
                //
            }
        });
        builder.create().show();

    }

    //下载apk文件
    private void downLadeApk() {

        if (mEquals) {
            //如果内存卡存在就下载到内存卡
            try {
                Response apk = HttpUtil.getImage(mInfoBeen.getApkurl());
                if (apk != null) {

                    mInputStream = apk.body().byteStream();
                    long max = apk.body().contentLength();
                    //设置进度条的最大值
                    mProgressDialog.setMax(100);
                    mAPKfile = new File(Environment.getExternalStorageDirectory(), "apktext.apk");
                    mOutputStream = new FileOutputStream(mAPKfile);
                    byte[] buffer = new byte[1024];
                    int len = 1;
                    while ((len = mInputStream.read(buffer)) != -1) {
                        mOutputStream.write(buffer, 0, len);
                        greelong += len;

                        //                        mProgressDialog.setProgress((int) (greelong/max)*100);
                        float v = greelong * 1.0f / max * 100;
                        mProgressDialog.setProgress((int) v);
                    }

                    mOutputStream.flush();
                    //对话框消失
                    mProgressDialog.dismiss();
                    //  6.提示用户安装
                    inStallApk();

                    // 7.安装完成
                } else {
                    //                    ToastMake.showToast("网路异常，更新失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
                //                ToastMake.showToast("网路异常，更新失败");
                //TODO：进入主界面
            } finally {

                //关流
                closeIO(mInputStream, mOutputStream);

            }
        } else {

        }
    }

    private void inStallApk() {
        //隐式意图安装的固定套路
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");

        //apk的文件名称
        Uri data = Uri.fromFile(mAPKfile);
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        //		startActivity(intent);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //监听客户是否安装,并且需要复写些onActivityResult方法
        startActivityForResult(intent, REQUEST_INSTALL);
        //  Process.killProcess(Process.myPid());
        /*
        *
  如果没有android.os.Process.killProcess(android.os.Process.myPid());最后不会提示完成、打开。没有这一句的话，安装完成后打开的不是新版本的apk

如果没有i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这一步的话，最后安装好了，点打开，是不会打开新版本应用的。*/


    }

    //关流
    private void closeIO(Closeable... io) {

        if (io != null) {
            for (int i = 0; i < io.length; i++) {

                if (io[i] != null) {
                    try {
                        io[i].close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        //TODO:进入主界面
                    }
                }
            }
        }
    }

    /**
     * 点击安装时是点击取消还是点击安装
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_INSTALL) {
            switch (resultCode) {
                //同意安装apk
                case Activity.RESULT_OK:

                    break;
                //取消安装apk
                case Activity.RESULT_CANCELED:

                    break;
            }
        }
    }

    /**
     * 1,先检查权限
     * 2，如果用户已经授权了，则可以直接登录
     * 3，如果用户没有，则申请，并自动跳转到相关界面
     */
    private void getUserPermission() {
    }

    protected String[] needPermissions = {
//            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    private static final int PERMISSON_REQUESTCODE = 0;
    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;
    @Override
    protected void onResume() {
        super.onResume();
        if(isNeedCheck){
            checkPermissions(needPermissions);
        }
    }


    /**
     *
     * @param
     * @since 2.5.0
     * requestPermissions方法是请求某一权限，
     */
    private void checkPermissions(String... permissions) {
        List<String> needRequestPermissonList = findDeniedPermissions(permissions);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(this,
                    needRequestPermissonList.toArray(
                            new String[needRequestPermissonList.size()]),
                    PERMISSON_REQUESTCODE);
        }
    }
    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     * checkSelfPermission方法是在用来判断是否app已经获取到某一个权限
     * shouldShowRequestPermissionRationale方法用来判断是否
     * 显示申请权限对话框，如果同意了或者不在询问则返回false
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this,
                    perm) != PackageManager.PERMISSION_GRANTED) {
                needRequestPermissonList.add(perm);
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(
                        this, perm)) {
                    needRequestPermissonList.add(perm);
                }
            }
        }
        return needRequestPermissonList;
    }
    /**
     * 检测是否所有的权限都已经授权
     * @param grantResults
     * @return
     * @since 2.5.0
     *
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    /**
     * 申请权限结果的回调方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }
    /**
     * 显示提示信息
     *
     * @since 2.5.0
     *
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("当前应用缺少必要权限。请点击\"设置\"-\"权限\"-打开所需权限。");

        // 拒绝, 退出应用
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton("设置",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }
    /**
     *  启动应用的设置
     *
     * @since 2.5.0
     *
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


}